﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Media;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AudioTest
{
    //https://www.cnblogs.com/gc2013/p/3929502.html
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        [DllImport("winmm.dll", EntryPoint = "mciSendString", CharSet = CharSet.Auto)]
        private static extern int mciSendString(
        string lpstrCommand,
        string lpstrReturnString,
        int uReturnLength,
        int hwndCallback);

        private void Form1_Load(object sender, EventArgs e)
        {
            this.txtPath.Text = @"D:\test.wav";            
        }


        private static void mciSendString(String cmd)
        {
            mciSendString(cmd, "", 0, 0);
        }

        private static void StartRecord()
        {
            mciSendString("close movie");
            mciSendString("open new type WAVEAudio alias movie");
            mciSendString("record movie");
        }

        private static void StopRecord(string filename)
        {
            mciSendString("stop movie");
            mciSendString("save movie " + filename);
            mciSendString("close movie");
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            //开始录音  
            StartRecord();
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            //停止录音  
            var path = this.txtPath.Text;
            //StopRecord(@"D:\test.wav");
            StopRecord(path);
        }

        private void btnPlay_Click(object sender, EventArgs e)
        {
            //播放录音   也可以适用window系统带的TTS（Text To Speech）播放录音  
            var path = this.txtPath.Text;
            //SoundPlayer sp = new SoundPlayer(@"D:\test.wav");
            SoundPlayer sp = new SoundPlayer(path);
            sp.PlaySync();
        }
    }
}
